package cn.cloud9.opencloud.common.util;

import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author OnCloud9
 * @description
 * @project Open-Cloud
 * @date 2022年04月16日 17:05
 */
public class WebUtil {

    private final static String AJAX_REQUEST_HEADER = "X-Requested-With";
    private final static String XML_HTTP_REQUEST = "XMLHttpRequest";

    /**
     * 获取客户端IP
     * 使用 Nginx等反向代理软件， 则不能通过 request.getRemoteAddr()获取 IP地址
     * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，
     * X-Forwarded-For中第一个非 unknown的有效IP字符串，则为真实IP地址
     * @param request
     * @return
     */
    public static String getRequestIp(HttpServletRequest request) {
        if (null == request) return "unknown";

        // 先按X-Forwarded-For获取
        String ipHeader = request.getHeader("X-Forwarded-For");
        if (!EmptyUtil.isEmptyString(ipHeader)) {
            final int INDEX = ipHeader.indexOf(",");
            return INDEX > 0 ? ipHeader.substring(0, INDEX) : ipHeader;
        }

        // 否则按X-Real-IP获取
        ipHeader = request.getHeader("X-Real-IP");
        if (!EmptyUtil.isEmptyString(ipHeader)) return ipHeader;

        ipHeader = request.getHeader("Proxy-Client-IP");
        if (!EmptyUtil.isEmptyString(ipHeader)) return ipHeader;

        ipHeader = request.getHeader("WL-Proxy-Client-IP");
        if (!EmptyUtil.isEmptyString(ipHeader)) return ipHeader;

        // 最后按远程地址拿IP
        ipHeader = request.getRemoteAddr();
        return ipHeader.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ipHeader;
    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        return XML_HTTP_REQUEST.equals( request.getHeader(AJAX_REQUEST_HEADER));
    }

    public static boolean isAjaxRequest(WebRequest request) {
        return XML_HTTP_REQUEST.equals( request.getHeader(AJAX_REQUEST_HEADER));
    }

    @SneakyThrows
    public static void sendJson(HttpServletResponse response, Object obj) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        final PrintWriter writer = response.getWriter();
        writer.write(JSONObject.toJSONString( obj));
        writer.flush();
        writer.close();
    }





}
